﻿using System;
using System.Web.Mvc;
using NHibernate;
using Web.DataAccess;
using Web.Extensions;
using Web.HelperClasses;
using Web.Security;
using Web.Model;
using Web.ViewModels;
using Web.HelperClasses.AvatarService;

namespace Web.Controllers
{
    public class NewsController : Controller
    {
        //
        // GET: /News/

        public ActionResult Index()
        {
            var news = new NewsSortedByDateQuery(userSession.CurrentUser).Load(session);
            ViewBag.isAdmin = (userSession.CurrentUser != null && userSession.CurrentUser.IsAdmin);
            return View(news);
        }

        public ActionResult Main()
        {
            var mainNews = new TopNewsQuery(userSession.CurrentUser, 3).Load(session);
            return View(mainNews);
        }

        [HttpGet]   
        public ActionResult Add()
        {
            if (!userSession.IsAuthenticated)
            {
                ViewBag.Message = "Чтобы добавить новость нужно залогиниться";
                return View("LoginNeeded");
            }
            if (!authz.Authorize(Operation.AddNews)) throw new UnauthorizedAccessException();
            return View();
        }

        [HttpPost]
        public ActionResult Add(AddNewsForm form)
        {
            if (!userSession.IsAuthenticated)
            {
                ViewBag.Message = "Чтобы добавить новость нужно залогиниться";
                return View("LoginNeeded");
            }
            if (!authz.Authorize(Operation.AddNews)) throw new UnauthorizedAccessException();
            if (!ModelState.IsValid) throw new ArgumentException("Неверный формат данных");

            var news = new News()
            {
                Title = form.Title,
                Content = form.Content,
                ShortContent = form.ShortContent,
                Author = userSession.CurrentUser,
                DateCreated = DateTime.Now,
                IsHidden = true
            };
            session.Save(news);
            AdminNotifier notifier = new AdminNotifier(session);
            notifier.NotifyNewsCreated(news);

            return Redirect(Url.Action("View", new { id = news.Id }));
        }
        
        public ActionResult View(int id)
        {
            var news = session.Get<News>(id);
            if (news == null) return View("NotFound");
            bool isMyNews = authz.Authorize(Operation.EditNews, news);
            if (news.IsHidden && !isMyNews) return View("Hidden");

            ViewBag.EditMode = isMyNews;

            return View(news);
        }

        [HttpPost]
        public void ChangeTitle(NewsTitleModel model)
        {
            if (!ModelState.IsValid) throw new ArgumentException("Неверный формат данных");
            var news = session.Get<News>(model.id);

            if (!authz.Authorize(Operation.EditNews, news)) throw new UnauthorizedAccessException();
            news.Title = model.editTitleText_input;
            session.Save(news);
        }

        [HttpPost]
        public void ChangeShortContent(NewsShortContentModel model)
        {
            if (!ModelState.IsValid) throw new ArgumentException("Неверный формат данных");
            var news = session.Get<News>(model.id);

            if (!authz.Authorize(Operation.EditNews, news)) throw new UnauthorizedAccessException();
            news.ShortContent = model.ShortContent;
            session.Save(news);
        }

        [HttpPost]
        public void ChangeContent(NewsContentModel model)
		{
            if (!ModelState.IsValid) throw new ArgumentException("Неверный формат данных");
            var news = session.Get<News>(model.id);

			if (!authz.Authorize(Operation.EditNews, news)) throw new UnauthorizedAccessException();
            news.Content = model.Content;
			session.Save(news);
		}

        [HttpPost]
        public void ShowHide(int id)
        {
            if (userSession.CurrentUser == null || !userSession.CurrentUser.IsAdmin) throw new UnauthorizedAccessException();
            var news = session.Get<News>(id);
            news.IsHidden = !news.IsHidden;
            session.Save(news);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            if (userSession.CurrentUser == null || !userSession.CurrentUser.IsAdmin) throw new UnauthorizedAccessException();
            var news = session.Get<News>(id);
            if (news == null) throw new ArgumentException("Новость не найдена");
            news.Clear(session);
            session.Delete(news);
            return RedirectToAction("Index");
        }

        public NewsController(ISession session, IUserSession userSession, IAuthorizationService authz, YandexFotki yandexFotki)
		{
			this.session = session;
			this.yandexFotki = yandexFotki;
			this.userSession = userSession;
		    this.authz = authz;
			this.avatarService = new NewsAvatarService(session, yandexFotki);
		}

		readonly ISession session;
		private readonly AvatarService avatarService;
		readonly IUserSession userSession;

		readonly IAuthorizationService authz;

		readonly YandexFotki yandexFotki;
    }
}
